package com.itheima.stock.service.imp;

import com.itheima.stock.common.domian.PermissionDomain;
import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.pojo.SysPermission;
import com.itheima.stock.service.PermissionService;
import com.itheima.stock.vo.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: siwukun
 * @date: 2022/06/10
 * @description:
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    /**
     * 查询所有权限列表
     *
     * @return
     */
    @Override
    public R<List<SysPermission>> getAllPermissions() {
        return R.ok(sysPermissionMapper.getAllPermissions());
    }

    /**
     * 添加权限时回显权限树
     * @return
     */
    @Override
    public R<List<PermissionDomain>> getPermissionTree() {
        List<SysPermission> permissionTree = sysPermissionMapper.getPermissionTree();
        //新建顶级菜单权限
        List<PermissionDomain> permissionList = new ArrayList<>();
        PermissionDomain permissionDomains = PermissionDomain.builder().id("0").title("顶级菜单").level(0).build();
        permissionList.add(permissionDomains);
        permissionList.addAll(getPermissionLevelTree(permissionTree,"0",1));
        return R.ok(permissionList);
    }
    /**
     * 递归设置级别，用于权限列表 添加/编辑 所属菜单树结构数据
     * @param permissions 权限集合
     * @param parentId 父级id
     * @param lavel 级别
     * @return
     */
    private List<PermissionDomain> getPermissionLevelTree(List<SysPermission> permissions, String parentId, int lavel) {
        List<PermissionDomain> result=new ArrayList<>();
        for (SysPermission permission : permissions) {
            if (permission.getType() !=3 && permission.getPid().equals(parentId)) {
                PermissionDomain per = new PermissionDomain();
                per.setId(permission.getId());
                per.setTitle(permission.getTitle());
                per.setLevel(lavel);
                result.add(per);
                result.addAll(getPermissionLevelTree(permissions,permission.getId(),lavel+1));
            }
        }
        return result;
    }
}
